package com.example.demo.service;

import com.example.demo.entity.PermissionEntity;
import com.example.demo.entity.UserEntity;
import com.example.demo.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;


@Component
@Slf4j
public class MemberUserDetailService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    /**
     *
     * @author HuangGaoTao
     * @date 2021/04/14 17:37
     * @param s
     * @return org.springframework.security.core.userdetails.UserDetails
     */

    //一旦进行登录就会回调这个方法    查到用户具有哪些权限
    //通过用户名来加载用户
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //接收传来的用户名  通过查找对应的用户
        UserEntity byUsername = userMapper.findByUsername(s);
        //如果用户为null 就返回空
        if(byUsername == null){
            return null;
        }

        //通过用户名查询该用户的所有权限
        List<PermissionEntity> permissionByUsername = userMapper.findPermissionByUsername(s);

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        //便利该用户的所有权限
        permissionByUsername.forEach(user->{
            //将用户的所有权限加到集合中
            grantedAuthorities.add(new SimpleGrantedAuthority(user.getPermTag()));
        });
        log.info(">>>authorities:{} <<<",grantedAuthorities);
       //将该用户所有权限添加到添加到实体类中的权限集合中
        byUsername.setAuthorities(grantedAuthorities);

        return byUsername;
    }
}
